/**
 * Copyright 2007 Bosco Curtu
 * Licensed under the Apache License, Version 2.0 (the "License"); 
 * you may not use this file except in compliance with the License. 
 * 
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an "AS IS" BASIS, 
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, 
 * either express or implied. 
 * 
 * See the License for the specific language governing permissions and limitations 
 * under the License.
*/

package com.bcurtu.amigo.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.bcurtu.amigo.pojo.Amigo;
import com.bcurtu.amigo.pojo.Message;
import com.bcurtu.amigo.services.AmigoInvisibleBO;


public class AmigoFormController extends CaptchaValidatorController {
	
	private Logger log =Logger.getLogger(this.getClass());
	
	private String errorView;
	
	private AmigoInvisibleBO bo;
	
	
	public String getErrorView() {
		return errorView;
	}
	public void setErrorView(String errorView) {
		this.errorView = errorView;
	}
	public AmigoInvisibleBO getBo() {
		return bo;
	}
	public void setBo(AmigoInvisibleBO bo) {
		this.bo = bo;
	}


	@Override
	protected void validateCommandObject(Object command, BindException errors) throws Exception {
	}


	@Override
	protected ModelAndView onSubmit(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, BindException errors) throws Exception {
		log.debug("onSubmit.");
		
		AmigoCommand cmd=(AmigoCommand)arg2;
		
		String[] names=cmd.getName();
		String[] emails=cmd.getEmail();
		Integer[] ids=cmd.getId();
		String[] excludes=cmd.getExclude();

		Message mes=new Message(cmd.getSubject(),cmd.getBody());
		
		List<Amigo> amigos=new ArrayList<Amigo>();
		
		for (int i=0;i<names.length;i++){
			Amigo amigo=new Amigo();
			amigo.setId(ids[i]);
			amigo.setName(names[i]);
			amigo.setEmail(emails[i]);
			amigo.setExclude(Integer.parseInt(excludes[i]));
			amigos.add(amigo);
			log.debug("Added a new Amigo:"+amigo);
		}
		
		log.debug("Sorteando amigos");
		
		try{
			bo.sortea(amigos, mes);			
			return new ModelAndView(getSuccessView());
		} catch (Exception ex){
			return new ModelAndView(getErrorView(),"exception",ex);			
		}
	}


//	@Override
//	protected Object formBackingObject(HttpServletRequest arg0) throws Exception {
//		AmigoCommand cmd=new AmigoCommand();
//		cmd.setAlias(aliasGenerator.generate());
//		return cmd;
//	}

	
	
	
}
